package com.zllkj.mm.util.common

import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import android.os.Build
import android.util.Log
import android.widget.ImageView
import androidx.databinding.BindingAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.request.animation.GlideAnimation
import com.bumptech.glide.request.target.SimpleTarget
import com.zllkj.mm.R
import com.zllkj.mm.common.ClientConfig
import io.reactivex.Observable
import kotlin.jvm.internal.Intrinsics

class PictureLoadUtil {
    companion object {
        @BindingAdapter("loadPic")
        fun loadPic(view:ImageView , url:String) {
            val token = "..."
            val url = ClientConfig.IMG_URL + url
            val glideUrl = GlideUrl(url) { mapOf(Pair("Authorization", "Bearer $token")) }

            Glide.with(view.context).load(glideUrl).asBitmap().placeholder(view.context.getDrawable(R.drawable.image_loading))
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE).into(object :SimpleTarget<Bitmap>() {
                        override fun onResourceReady(p0: Bitmap?, p1: GlideAnimation<in Bitmap>?) {
                            view.setImageBitmap(p0)
                        }
                    })

        }

        fun loadImageFromOnLineUrl(imageView: ImageView,url: String){
            imageView.setImageBitmap(retriveVideoFrameFromVideo(url))
        }

        fun retriveVideoFrameFromVideo(videoPath: String?): Bitmap? {
            var bitmap: Bitmap? = null
            var mediaMetadataRetriever: MediaMetadataRetriever? = null
            try {
                mediaMetadataRetriever = MediaMetadataRetriever()
                if (Build.VERSION.SDK_INT >= 14) mediaMetadataRetriever.setDataSource(videoPath, HashMap<String, String>()) else mediaMetadataRetriever.setDataSource(videoPath)
                //   mediaMetadataRetriever.setDataSource(videoPath);
                bitmap = mediaMetadataRetriever.getFrameAtTime()
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                if (mediaMetadataRetriever != null) {
                    mediaMetadataRetriever.release()
                }
            }
            return bitmap
        }

    }
}